package daoImpl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import utility.Utility;
import dao.EmployeeDAO;
import domain.Employee;

public class EmployeeDaoImpl implements EmployeeDAO {

	protected static Logger log = Logger.getLogger(EmployeeDaoImpl.class);
	
	@Resource(name = "sessionFactory")
	SessionFactory sessionFactory;

	@Override
	public void addEmployee(Employee employee) {
		log.debug("Adding a new employee : " + employee.getFirstName() + " ...");
		Session session = Utility.getSession(sessionFactory);
		session.save(employee);
		log.debug("Added new employee successfully.");
	}

	@Override
	public void editEmployee(Employee employee) {
		log.debug("Editting an exist employee : " + employee.getFirstName() + " ...");
		Session session = Utility.getSession(sessionFactory);
		Employee existEmp = (Employee) session.get(Employee.class, employee.getEmployeeID());
		existEmp.setAddress(employee.getAddress());
		existEmp.setFirstName(employee.getFirstName());
		existEmp.setLastName(employee.getLastName());
		existEmp.setPhone(employee.getPhone());
		existEmp.setYearOfBirth(employee.getYearOfBirth());
		session.save(existEmp);
		log.debug("Updated an exist employee : " + employee.getFirstName());
	}

	@Override
	public void disableEmployee(Employee employee) {
		log.debug("Disabling an exist employee : " + employee.getFirstName() + " ...");
		Session session = Utility.getSession(sessionFactory);
		employee.setStatus("N");
		session.save(employee);
		log.debug("Employee : " + employee.getFirstName() + " was disbaled");
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Employee> searchEmployee(String strSearch) {
		log.debug("Search employee ...");
		Session session = Utility.getSession(sessionFactory);
		String search = "FROM Employee where firstName like %:firstname% or lastName like %:lastName%";
		Query query = session.createQuery(search);
		query.setParameter("firstName", strSearch);
		query.setParameter("lastName", strSearch);
		List<Employee> listResult = query.list();
		if (CollectionUtils.isNotEmpty(listResult)) {
			log.debug("Return a list employee size : " + listResult.size());
			return listResult;
		} else {
			log.debug("No records has been found.");
			return null;
		}
	}
}
